<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="psOrderId">
        <el-input
          v-model="queryParams.psOrderId"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.logistics_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="日期范围" prop="dateRange">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          size="small"
          @change="handleDateRangeChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="更改用户" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入更改用户"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-camera"
          size="mini"
          class="scan-btn"
          title="扫一扫"
          @click="handleScan"
        >扫一扫</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['supply:logistics:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['supply:logistics:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['supply:logistics:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['supply:logistics:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="logisticsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="订单编号" align="center" prop="psOrderNum" width="180"/>
      <el-table-column label="当前状态" align="center" prop="statusDesc" width="120">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ scope.row.statusDesc }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货地址" align="center" prop="address"/>
<!--      <el-table-column label="操作人" align="center" prop="nickName">-->
<!--        <template slot-scope="scope">-->
<!--          {{ scope.row.nickName || '暂无' }}-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="商品信息" align="center">
        <template slot-scope="scope">
          <el-popover
            v-if="scope.row.prodInfoVOList && scope.row.prodInfoVOList.length"
            placement="right"
            width="400"
            trigger="hover">
            <div class="product-list">
              <div v-for="(item, index) in scope.row.prodInfoVOList" :key="index" class="product-item">
                <el-image
                  :src="item.imageUrl && item.imageUrl.includes(',') ? item.imageUrl.split(',')[0] : item.imageUrl"
                  :preview-src-list="item.imageUrl ? item.imageUrl.split(',') : []"
                  style="width: 50px; height: 50px"
                  fit="cover">
                </el-image>
                <div class="product-info">
                  <div class="product-name">{{ item.name }}</div>
                  <div class="product-detail">
                    <span>数量: {{ item.quantity }}</span>
                    <span>单价: ￥{{ item.unitPrice }}</span>
                  </div>
                </div>
              </div>
            </div>
            <el-button slot="reference" type="text">查看商品({{ scope.row.prodInfoVOList.length }})</el-button>
          </el-popover>
          <span v-else>暂无商品信息</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewDetail(scope.row)"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['supply:logistics:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['supply:logistics:remove']"
          >删除
          </el-button>
          <el-button
            v-if="scope.row.status == 0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handlePackageDone(scope.row)"
            v-hasPermi="['supply:logistics:exclude:buyer']"
          >点击打包完成
          </el-button>

          <el-button
            v-if="scope.row.status == 1"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleSending(scope.row)"
            v-hasPermi="['supply:logistics:exclude:buyer']"
          >点击配送中
          </el-button
          >

          <el-button
            v-if="scope.row.status == 2"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleSendDone(scope.row)"
            v-hasPermi="['supply:logistics:exclude:buyer']"
          >点击送达
          </el-button
          >

          <el-button
            v-if="scope.row.status == 3"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleSigned(scope.row)"
            v-hasPermi="['supply:logistics:buyer']"
          >点击签收
          </el-button>

          <!--退单的流程与按钮 -->
          <el-button
            v-if="scope.row.status == -1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCancelSend(scope.row)"
            v-hasPermi="['supply:logistics:send']"
          >点击退单配送
          </el-button>

          <el-button
            v-if="scope.row.status == -2"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleCancelSendDone(scope.row)"
            v-hasPermi="['supply:logistics:send']"
          >点击退单送达
          </el-button
          >

          <el-button
            v-if="scope.row.status == -3"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleCancelSigned(scope.row)"
            v-hasPermi="['supply:logistics:warehouse']"
          >退单签收
          </el-button>




          <!--          <el-button-->
          <!--            v-if="scope.row.status == 4"-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-delete"-->
          <!--            v-hasPermi="['supply:logistics:exclude:buyer']"-->
          <!--          >完成-->
          <!--          </el-button>-->

          <el-button
            v-if="scope.row.status >=0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            v-hasPermi="['supply:logistics:buyer']"
            @click="handleCancleOrder(scope.row)"
          >取消订单
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 物流详情对话框 -->
    <el-dialog title="物流详情" :visible.sync="detailOpen" width="30%" append-to-body>
      <div class="logistics-detail">
        <!-- 顶部：物流信息和订单信息 -->
        <div class="top-section">
          <!-- 物流信息 -->
          <div class="logistics-info" v-if="logisticsHistory && logisticsHistory.length > 0">
            <h3>物流信息</h3>
            <el-timeline>
              <el-timeline-item
                v-for="(activity, index) in logisticsHistory"
                :key="index"
                :timestamp="parseTime(activity.createTime, '{y}-{m}-{d} {h}:{i}')"
                :type="getTimelineItemType(activity.status)"
              >
                <div class="timeline-content">
                  <span class="status-text">{{ activity.statusDesc }}</span>
                  <div class="operator" v-if="activity.userId" style="font-size: 12px">
                    操作人 ：{{ activity.userName || activity.nickName || activity.userId || '未知' }}
                  </div>
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>

          <!-- 订单信息 -->
          <div class="order-info">
            <h3>订单信息</h3>
            <p v-if="currentOrder.psOrderId">订单号：{{ currentOrder.psOrderId }}</p>
            <p v-if="currentOrder.status">状态：{{ currentOrder.statusDesc }}</p>
            <p v-if="currentOrder.createTime">最新更新时间：{{
                parseTime(currentOrder.createTime, '{y}-{m}-{d} {h}:{i}')
              }}</p>
            <p v-if="currentOrder.address">地址：{{ currentOrder.address }}</p>
            <p v-if="currentOrder.customerName">采购商：{{ currentOrder.customerName }}</p>
            <p v-if="currentOrder.customerPhone">采购商电话：{{ currentOrder.customerPhone }}</p>
            <p v-if="currentOrder.nickName || currentOrder.userName">
              操作人：{{ currentOrder.userName || currentOrder.nickName || currentOrder.userId || '未知' }}
            </p>
          </div>
        </div>

        <!-- 底部：商品详情 -->
        <div class="product-info" v-if="currentOrder && currentOrder.prodInfoVOList && currentOrder.prodInfoVOList.length > 0">
          <h3>商品信息</h3>
          <el-card v-for="(item, index) in currentOrder.prodInfoVOList"
                   :key="index"
                   class="product-card"
                   shadow="hover">
            <div class="product-item">
              <div class="image-list" v-if="item.imageUrl">
                <el-image
                  v-for="(url, urlIndex) in item.imageUrl.split(',')"
                  :key="urlIndex"
                  :src="url"
                  :preview-src-list="item.imageUrl.split(',')"
                  fit="cover"
                  class="product-image">
                </el-image>
              </div>
              <div class="product-details">
                <h4>{{ item.name }}</h4>
                <el-descriptions :column="2" border size="small">
                  <el-descriptions-item label="商品品牌">{{ item.brand }}</el-descriptions-item>
                  <el-descriptions-item label="商品类型">{{ item.type }}</el-descriptions-item>
                  <el-descriptions-item label="最小单位">{{ item.minUnit }}</el-descriptions-item>
                  <el-descriptions-item label="商品性质">{{ item.nature }}</el-descriptions-item>
                  <el-descriptions-item label="单价">￥{{ item.unitPrice }}</el-descriptions-item>
                  <el-descriptions-item label="数量">{{ item.quantity }}</el-descriptions-item>
                  <el-descriptions-item label="小计" :span="2">
                    <span class="total-price">￥{{ (item.unitPrice * item.quantity).toFixed(2) }}</span>
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </div>
          </el-card>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改物流对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单号" prop="psOrderId">
          <el-input v-model="form.psOrderId" placeholder="请输入订单号"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in dict.type.logistics_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="更改用户" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入更改用户"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 取消订单对话框 -->
    <el-dialog title="取消订单" :visible.sync="cancelOrderOpen" width="500px" append-to-body>
      <el-form ref="cancelForm" :model="cancelForm" :rules="cancelRules" label-width="80px">
        <el-form-item label="订单号" prop="orderId">
          <el-input v-model="cancelForm.orderId" disabled />
        </el-form-item>
        <el-form-item label="退单原因" prop="reason">
          <el-input
            type="textarea"
            v-model="cancelForm.reason"
            placeholder="请输入退单原因"
            :rows="4"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCancelOrder">确 定</el-button>
        <el-button @click="cancelOrderOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listLogistics,
  getLogistics,
  delLogistics,
  addLogistics,
  updateLogistics,
  listLogisticsById
} from "@/api/supply/logistics";
import request from "@/utils/request";
import {listUsernameByIds} from "@/api/system/user";

export default {
  name: "Logistics",
  dicts: ['logistics_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物流表格数据
      logisticsList: [],
      //所有物流信息分组
      logisticsGroup: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        psOrderId: null,
        status: null,
        userId: null,
        beginTime: null,
        endTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        psOrderId: [
          {required: true, message: "订单号不能为空", trigger: "blur"}
        ],
        status: [
          {required: true, message: "状态不能为空", trigger: "change"}
        ],
        userId: [
          {required: true, message: "更改用户不能为空", trigger: "blur"}
        ]
      },
      // 新增的数据
      detailOpen: false,
      currentOrder: {},
      logisticsHistory: [],

      // 取消订单相关数据
      cancelOrderOpen: false,
      cancelForm: {
        orderId: null,
        reason: ''
      },
      cancelRules: {
        reason: [
          { required: true, message: "退单原因不能为空", trigger: "blur" },
          { min: 2, max: 200, message: "退单原因长度在 2 到 200 个字符之间", trigger: "blur" }
        ]
      },
      dateRange: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询物流列表 */
    async getList() {
      this.loading = true;
      // 初始化数据，防止渲染错误
      this.logisticsList = [];

      // 处理日期格式
      const params = { ...this.queryParams };

      // 如果存在开始日期和结束日期，添加时间部分
      if (params.beginTime) {
        params.beginTime = params.beginTime + ' 00:00:00';
      }
      if (params.endTime) {
        params.endTime = params.endTime + ' 23:59:59';
      }

      listLogistics(params).then(response => {
        if (response && response.rows) {
          // 直接使用后端返回的数据和总条数
          this.logisticsList = response.rows;
          this.total = response.total || 0; // 使用后端返回的总条数，如果没有则默认为0

          // 保存分组信息，可能在其他功能中有用
          const grouped = {};
          response.rows.forEach(item => {
            if (item && item.psOrderId) { // 添加安全检查
              const key = item.psOrderId;
              grouped[key] = grouped[key] || [];
              grouped[key].push(item);
            }
          });

          // 对每组数据按时间倒序排序
          Object.values(grouped).forEach(group => {
            group.sort((a, b) => (b.createTime || '').localeCompare(a.createTime || ''));
          });
          this.logisticsGroup = grouped;
        } else {
          this.logisticsList = [];
          this.total = 0;
          this.logisticsGroup = {};
        }

        this.loading = false;
      }).catch(error => {
        console.error("获取物流列表失败:", error);
        this.$modal.msgError("获取物流列表失败");
        this.logisticsList = [];
        this.total = 0;
        this.logisticsGroup = {};
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        psOrderId: null,
        status: null,
        createTime: null,
        userId: null
      };
      this.resetForm("form");
    },
    async handleCancleOrder(row) {
      if (!row || !row.psOrderId) {
        this.$modal.msgError("订单信息不完整，无法取消");
        return;
      }

      this.cancelForm = {
        orderId: row.psOrderId,
        reason: ''
      };
      this.cancelOrderOpen = true;
    },
    async handlePackageDone(row) {
      if (!row || !row.psOrderId) {
        this.$modal.msgError("订单信息不完整，无法完成打包");
        return;
      }

      this.loading = true;
      try {
        let res = await request({
          url: '/supply/logistics/package/done?orderId=' + row.psOrderId,
          method: 'post',
        });
        if (res.code === 200) {
          this.$modal.msgSuccess("打包完成");
        }
        await this.getList();
      } catch (error) {
        console.error("完成打包失败:", error);
        this.$modal.msgError("完成打包失败");
      } finally {
        this.loading = false;
      }
    },
    async handleSending(row) {
      if (!row || !row.psOrderId) {
        this.$modal.msgError("订单信息不完整，无法开始配送");
        return;
      }

      this.loading = true;
      try {
        let res = await request({
          url: '/supply/logistics/sender/ing?orderId=' + row.psOrderId,
          method: 'post',
        });
        if (res.code === 200) {
          this.$modal.msgSuccess("开始配送");
        }
        await this.getList();
      } catch (error) {
        console.error("开始配送失败:", error);
        this.$modal.msgError("开始配送失败");
      } finally {
        this.loading = false;
      }
    },
    async handleSendDone(row) {
      if (!row || !row.psOrderId) {
        this.$modal.msgError("订单信息不完整，无法完成配送");
        return;
      }

      this.loading = true;
      try {
        let res = await request({
          url: '/supply/logistics/sender/done?orderId=' + row.psOrderId,
          method: 'post',
        });
        if (res.code === 200) {
          this.$modal.msgSuccess("配送完成");
        }
        await this.getList();
      } catch (error) {
        console.error("完成配送失败:", error);
        this.$modal.msgError("完成配送失败");
      } finally {
        this.loading = false;
      }
    },
    async handleSigned(row) {
      if (!row || !row.psOrderId) {
        this.$modal.msgError("订单信息不完整，无法签收");
        return;
      }

      this.loading = true;
      try {
        let res = await request({
          url: '/supply/logistics/sign/done?orderId=' + row.psOrderId,
          method: 'post',
        });
        if (res.code === 200) {
          this.$modal.msgSuccess("签收成功");
        }
        await this.getList();
      } catch (error) {
        console.error("签收失败:", error);
        this.$modal.msgError("签收失败");
      } finally {
        this.loading = false;
      }
    },
    async handleCancelSend(row) {
      if (!row || !row.psOrderId) {
        this.$modal.msgError("订单信息不完整，无法开始配送");
        return;
      }

      this.loading = true;
      try {
        let res = await request({
          url: '/supply/logistics/cancel/sender/ing?orderId=' + row.psOrderId,
          method: 'post',
        });
        if (res.code === 200) {
          this.$modal.msgSuccess("开始配送");
        }
        await this.getList();
      } catch (error) {
        console.error("开始配送失败:", error);
        this.$modal.msgError("开始配送失败");
      } finally {
        this.loading = false;
      }
    },
    async handleCancelSendDone(row) {
      if (!row || !row.psOrderId) {
        this.$modal.msgError("订单信息不完整，无法完成配送");
        return;
      }

      this.loading = true;
      try {
        let res = await request({
          url: '/supply/logistics/cancel/sender/done?orderId=' + row.psOrderId,
          method: 'post',
        });
        if (res.code === 200) {
          this.$modal.msgSuccess("配送完成");
        }
        await this.getList();
      } catch (error) {
        console.error("完成配送失败:", error);
        this.$modal.msgError("完成配送失败");
      } finally {
        this.loading = false;
      }
    },
    async handleCancelSigned(row) {
      if (!row || !row.psOrderId) {
        this.$modal.msgError("订单信息不完整，无法签收");
        return;
      }

      this.loading = true;
      try {
        let res = await request({
          url: '/supply/logistics/cancel/sign/done?orderId=' + row.psOrderId,
          method: 'post',
        });
        if (res.code === 200) {
          this.$modal.msgSuccess("签收成功");
        }
        await this.getList();
      } catch (error) {
        console.error("签收失败:", error);
        this.$modal.msgError("签收失败");
      } finally {
        this.loading = false;
      }
    },


    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.beginTime = null;
      this.queryParams.endTime = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物流";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getLogistics(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改物流";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateLogistics(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLogistics(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除物流编号为"' + ids + '"的数据项？').then(function () {
        return delLogistics(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('supply/logistics/export', {
        ...this.queryParams
      }, `logistics_${new Date().getTime()}.xlsx`)
    },
    /** 查看详情按钮操作 */
    async handleViewDetail(row) {
      if (!row || !row.psOrderId) {
        this.$modal.msgError("订单信息不完整，无法查看详情");
        return;
      }

      try {
        this.detailOpen = true;
        this.loading = true;
        // 初始化，防止显示上一次的数据
        this.logisticsHistory = [];
        this.currentOrder = {};

        // 调用API获取物流详细信息
        const response = await listLogisticsById(row.psOrderId);
        if (response && response.data && response.data.length) {
          // 按时间倒序排序
          this.logisticsHistory = response.data.sort((a, b) =>
            new Date(b.createTime || 0) - new Date(a.createTime || 0)
          );

          // 收集所有操作人ID
          const userIds = this.logisticsHistory
            .filter(item => item.userId)
            .map(item => item.userId);

          // 如果有操作人ID，则获取用户名
          if (userIds.length > 0) {
            const uniqueUserIds = [...new Set(userIds)]; // 去重并转为逗号分隔字符串
            console.log("获取用户名: ", uniqueUserIds)
            try {
              // 导入user模块并调用方法获取用户名
              const userResponse = await listUsernameByIds(uniqueUserIds);
              console.log("userResponse",userResponse)

              if (userResponse.code === 200 && userResponse.data) {
                // 创建用户ID到用户名的映射
                const userMap = {};
                userResponse.data.forEach(user => {
                  userMap[user.userId] = user.userName || user.nickName || '未知用户';
                });

                // 更新物流记录中的操作人信息
                this.logisticsHistory.forEach(item => {
                  if (item.userId && userMap[item.userId]) {
                    item.userName = userMap[item.userId];
                  }
                });

                // 更新当前订单操作人信息
                if (this.currentOrder.userId && userMap[this.currentOrder.userId]) {
                  this.currentOrder.userName = userMap[this.currentOrder.userId];
                }
              }
            } catch (error) {
              console.error("获取用户名失败:", error);
            }
          }

          // 设置当前订单信息为最新的一条记录
          this.currentOrder = this.logisticsHistory[0] || {};
        } else {
          this.$modal.msgInfo("没有找到相关物流记录");
        }
      } catch (error) {
        this.$modal.msgError("获取物流详情失败");
        console.error("获取物流详情失败:", error);
      } finally {
        this.loading = false;
      }
    },
    /** 获取时间轴项目类型 */
    getTimelineItemType(status) {
      const statusMap = {
        0: 'primary',   // 待发货
        1: 'success',   // 已发货
        2: 'warning',   // 运输中
        3: 'success',   // 已送达
        '-1': 'primary',   // 已送达
        '-2': 'primary',   // 已送达
        '-3': 'primary',   // 已送达
        4: 'danger'     // 异常
      };
      return statusMap[status] || 'info';
    },
    /** 获取状态标签类型 */
    getStatusType(status) {
      const statusMap = {
        0: 'info',    // 正在打包
        1: 'primary', // 打包完成
        2: 'warning', // 配送中
        3: 'success', // 已送达
        '-1': 'primary',   // 已退单
        '-2': 'primary',   // 配送中
        '-3': 'primary',   // 已送达
        4: 'danger'   // 已取消
      };
      return statusMap[status] || 'info';
    },
    // 提交取消订单
    submitCancelOrder() {
      this.$refs["cancelForm"].validate(async valid => {
        if (valid) {
          this.loading = true;
          try {
            let res = await request({
              url: '/supply/psorders/cancel/' + this.cancelForm.orderId,
              method: 'put',
              params: {
                reason: this.cancelForm.reason
              }
            });
            if (res.code === 200) {
              this.$modal.msgSuccess("取消订单成功");
              this.cancelOrderOpen = false;
              await this.getList();
            }
          } catch (error) {
            console.error("取消订单失败:", error);
            this.$modal.msgError("取消订单失败");
          } finally {
            this.loading = false;
          }
        }
      });
    },
    handleDateRangeChange(value) {
      if (value) {
        this.queryParams.beginTime = value[0];
        this.queryParams.endTime = value[1];
      } else {
        this.queryParams.beginTime = null;
        this.queryParams.endTime = null;
      }
    },
    handleScan() {
      this.$modal.msgInfo("扫一扫功能暂未开放，敬请期待！");
      // 在移动端环境可以调用原生扫码功能
      /*
      if (this.$isApp) {
        // 调用原生扫码功能，这里仅为示例
        plus.barcode.scan({
          conserve: true,
          filename: '_doc/barcode/'
        }, (type, result) => {
          // 扫码成功，处理结果
          this.queryParams.psOrderId = result;
          this.handleQuery();
        }, (error) => {
          this.$modal.msgError('扫码失败：' + error.message);
        });
      } else {
        this.$modal.msgInfo("请在移动端使用扫码功能");
      }
      */
    }
  }
};
</script>

<style lang="scss" scoped>
.logistics-detail {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;

  .top-section {
    display: flex;
    justify-content: space-between; // 物流信息在左，订单信息在右

    .logistics-info, .order-info {
      flex: 1;
      background: #f9f9f9;
      border: 1px solid #ebeef5;
      padding: 20px;
      border-radius: 5px;

      h3 {
        margin: 0 0 10px;
        font-size: 16px;
        color: #303133;
      }

      p {
        margin: 5px 0;
        color: #606266;
      }
    }
  }

  .product-info {
    background: #f9f9f9;
    border: 1px solid #ebeef5;
    padding: 20px;
    border-radius: 5px;

    .item-info {
      display: flex;
      align-items: center; // 垂直居中对齐
      gap: 20px;
      margin-bottom: 10px;

      .product-image {
        display: flex;
        align-items: center;
      }

      .product-details {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;

        p {
          margin: 5px 0;
        }
      }
    }
  }
}

::v-deep .el-timeline-item__timestamp {
  color: #909399;
  font-size: 13px;
}

.product-list {
  .product-item {
    display: flex;
    align-items: center;
    padding: 10px;
    border-bottom: 1px solid #EBEEF5;

    &:last-child {
      border-bottom: none;
    }

    .product-info {
      margin-left: 10px;
      flex: 1;

      .product-name {
        font-weight: bold;
        margin-bottom: 5px;
      }

      .product-detail {
        color: #666;
        font-size: 13px;

        span {
          margin-right: 15px;
        }
      }
    }
  }
}

.logistics-detail {
  .product-card {
    margin-bottom: 15px;

    .product-item {
      .image-list {
        display: flex;
        gap: 10px;
        margin-bottom: 15px;
        overflow-x: auto;
        padding: 5px;

        .product-image {
          width: 80px;
          height: 80px;
          border-radius: 4px;
          flex-shrink: 0;
        }
      }

      .product-details {
        h4 {
          margin: 0 0 15px;
          color: #303133;
        }

        .total-price {
          color: #F56C6C;
          font-size: 16px;
          font-weight: bold;
        }
      }
    }
  }
}

// 状态标签样式
::v-deep .el-tag {
  &.el-tag--success {
    background-color: #f0f9eb;
  }
  &.el-tag--warning {
    background-color: #fdf6ec;
  }
  &.el-tag--danger {
    background-color: #fef0f0;
  }
}

/* 扫一扫按钮样式 */
.scan-btn {
  margin-left: 5px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.scan-btn i {
  margin-right: 4px;
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .el-form-item {
    margin-bottom: 10px;
    width: 100%;
  }

  .el-date-picker {
    width: 100%;
  }

  .el-form-item__content {
    width: 100%;
  }

  .el-button + .el-button {
    margin-left: 5px;
  }

  .date-range-picker {
    display: flex;
    align-items: center;
    width: 100%;
  }
}
</style>
